package zxd.util;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.exception.ExceptionUtils;

/**
 * Created by filon51 on 2017/7/16.
 */
public class Message {

    private static final String STATUS = "status";
    private static final String STATUS_SUCC = "success";
    private static final String STATUS_FAIL = "fail";
    private static final String ERROR = "errMsg";
    private static final String ERROR_TRACE = "errTrace";
    private static final String MSG = "msg";
    private static final String DATABODY = "data";


    public static Map succMap(Object dataBody) {
        HashMap message = new HashMap();
        message.put(STATUS, STATUS_SUCC);
        if (dataBody != null) {
            message.put(DATABODY, dataBody);
        }
        System.out.println("message="+message.toString());
        return message;
    }
    public static Map succMap(Object dataBody,String succMSG) {
        HashMap message = new HashMap();
        message.put(STATUS, STATUS_SUCC);
        message.put(MSG, succMSG);
        if (dataBody != null) {
            message.put(DATABODY, dataBody);
        }
        return message;

    }


    public static Map failMap(Error error) {
        HashMap message = new HashMap();
        message.put(STATUS, STATUS_FAIL);

        String regEx = "Caused by:(.*)";
        Pattern pat = Pattern.compile(regEx);
        Matcher mat = pat.matcher(ExceptionUtils.getStackTrace(error));
        while (mat.find()) {
            message.put(ERROR, mat.group(mat.groupCount()));
        }
        message.put(ERROR_TRACE, ExceptionUtils.getStackTrace(error));
        return message;
    }


    public static Map failMap(String error) {
        HashMap message = new HashMap();
        message.put(STATUS, STATUS_FAIL);

        message.put(ERROR, error);

        message.put(ERROR_TRACE, error);
        return message;
    }

    public static Map failMap(String errorString, Error error) {
        HashMap message = new HashMap();
        message.put(STATUS, STATUS_FAIL);
        String regEx = "Caused by:(.*)";
        Pattern pat = Pattern.compile(regEx);
        Matcher mat = pat.matcher(ExceptionUtils.getStackTrace(error));
        while (mat.find()) {
            message.put(ERROR, errorString + "\n" + mat.group(mat.groupCount()));
        }

        message.put(ERROR_TRACE, ExceptionUtils.getStackTrace(error));
        return message;
    }
}
